﻿using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Routing;
using Isis.Handlers;
using Isis.Parsers.Impl;

namespace Isis
{
    public class ControlPanel : IHttpHandlerFactory
    {
        private readonly RouteDataParser _routeDataParser;

        public ControlPanel() : this(new RouteDataParser())
        {            
        }

        private ControlPanel(RouteDataParser routeDataParser)
        {
            _routeDataParser = routeDataParser;
        }

        public virtual IHttpHandler GetHandler(RequestContext requestContext)
        {
            //
            // The request resource is determined by looking up the
            // value of the PATH_INFO server variable.
            //
            string resource = requestContext.HttpContext.Request.PathInfo.Length == 0
                                  ? string.Empty
                                  : requestContext.HttpContext.Request.PathInfo.Substring(1);

            resource = resource.ToLower(CultureInfo.InvariantCulture);

            string controller = _routeDataParser.GetController(requestContext);
            if (controller == "stylesheet")
                return new ManifestResourceHandler("Isis.css", "text/css", Encoding.GetEncoding("Windows-1252"));

            if (controller == "npBrandingBkd")
                return new ManifestResourceHandler("npBrandingBkd.png", "image/png", Encoding.GetEncoding("Windows-1252"));

            if (controller == "npBrandingLogo")
                return new ManifestResourceHandler("npBrandingLogo.png", "image/png", Encoding.GetEncoding("Windows-1252"));

            if (resource.Length == 0) return new ControlPanelHandler(requestContext);
            if (resource.Equals(English.Command_Home)) return new ControlPanelHandler(requestContext);

            if (resource.Equals(English.Command_StyleSheet))
                return new ManifestResourceHandler("Isis.css",
                                                   "text/css", Encoding.GetEncoding("Windows-1252"));

            // if we made it this far without finding a match, we're not going to find one...
            throw new HttpException(404, "Resource not found.");
        
        }

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            throw new NotImplementedException();
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}